const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');
const path = require('path');
const fs = require('fs');

// 导入路由
const uploadRouter = require('./routes/upload');
const songsRouter = require('./routes/songs');
const songersRouter = require('./routes/songers');

const app = new Koa();
const router = new Router();

// 中间件配置
app.use(cors());
app.use(bodyParser());

// 简单的静态文件服务
app.use(async (ctx, next) => {
    if (ctx.path === '/upload-test.html') {
        const filePath = path.join(__dirname, 'public', 'upload-test.html');
        if (fs.existsSync(filePath)) {
            ctx.type = 'text/html';
            ctx.body = fs.readFileSync(filePath, 'utf8');
            return;
        }
    }
    await next();
});

// 音频文件服务
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/uploads/')) {
        const filePath = path.join(__dirname, ctx.path);
        
        if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
            const ext = path.extname(filePath).toLowerCase();
            
            // 设置正确的 MIME 类型
            switch (ext) {
                case '.mp3':
                    ctx.type = 'audio/mpeg';
                    break;
                case '.wav':
                    ctx.type = 'audio/wav';
                    break;
                case '.m4a':
                    ctx.type = 'audio/mp4';
                    break;
                default:
                    ctx.type = 'audio/mpeg';
            }
            
            // 支持范围请求
            const stat = fs.statSync(filePath);
            const range = ctx.headers.range;
            
            if (range) {
                const parts = range.replace(/bytes=/, "").split("-");
                const start = parseInt(parts[0], 10);
                const end = parts[1] ? parseInt(parts[1], 10) : stat.size - 1;
                const chunksize = (end - start) + 1;
                
                ctx.status = 206;
                ctx.set({
                    'Content-Range': `bytes ${start}-${end}/${stat.size}`,
                    'Accept-Ranges': 'bytes',
                    'Content-Length': chunksize,
                    'Cache-Control': 'no-cache'
                });
                
                ctx.body = fs.createReadStream(filePath, { start, end });
            } else {
                ctx.set({
                    'Content-Length': stat.size,
                    'Accept-Ranges': 'bytes',
                    'Cache-Control': 'no-cache'
                });
                ctx.body = fs.createReadStream(filePath);
            }
            return;
        }
    }
    await next();
});

// 健康检查
router.get('/health', async (ctx) => {
    ctx.body = { 
        status: 'ok', 
        message: '音乐服务器运行正常',
        timestamp: new Date().toISOString()
    };
});

// 根路由
router.get('/', async (ctx) => {
    ctx.body = { 
        message: '🎵 音乐管理系统API服务器', 
        version: '2.0.0',
        endpoints: {
            upload: 'POST /api/upload/complete - 完整音频上传',
            songs: 'GET/POST/DELETE /api/songs - 歌曲管理',
            songers: 'GET/POST/DELETE /api/songers - 歌手管理',
            audio: 'GET /api/audio/:id - 音频播放',
            test: 'GET /upload-test.html - 上传测试页面'
        }
    };
});

// 使用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 注册各模块路由
app.use(uploadRouter.routes());
app.use(uploadRouter.allowedMethods());

app.use(songsRouter.routes());
app.use(songsRouter.allowedMethods());

app.use(songersRouter.routes());
app.use(songersRouter.allowedMethods());

// 启动服务器
const PORT = process.env.PORT || 3000;
const HOST = '0.0.0.0';

// 确保上传目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
    console.log('✓ uploads目录已创建');
}

app.listen(PORT, HOST, () => {
    console.log('\n🎵 音乐管理系统服务器已启动');
    console.log('=====================================');
    console.log(`📡 本地地址: http://localhost:${PORT}`);
    console.log(`📡 网络地址: http://172.29.99.148:${PORT}`);
    console.log(`📁 上传目录: ${uploadsDir}`);
    console.log('\n🚀 可用接口:');
    console.log(`   - 完整上传: POST http://localhost:${PORT}/api/upload/complete`);
    console.log(`   - 歌曲管理: http://localhost:${PORT}/api/songs`);
    console.log(`   - 歌手管理: http://localhost:${PORT}/api/songers`);
    console.log(`   - 测试页面: http://localhost:${PORT}/upload-test.html`);
    console.log('=====================================');
    console.log('✅ 服务器已准备就绪！');
});

// 优雅关闭处理
process.on('SIGINT', () => {
    console.log('\n🛑 收到SIGINT信号，正在关闭服务器...');
    process.exit(0);
});

process.on('SIGTERM', () => {
    console.log('\n🛑 收到SIGTERM信号，正在关闭服务器...');
    process.exit(0);
});